<?php
class LoggerFactory extends Logger {

	private static $instance;
	
	public static $debug = 1;
	public static $info = 2;
	public static $warning = 3;
	public static $error = 4;
	public static $fatal = 5;
	
	public static $all = 0;
	public static $none = 10;
	
	private static $logLevelNameArray = array(	1 => 'DEBUG',
												2 => 'INFO',
												3 => 'WARNING',
												4 => 'ERROR',
												5 => 'FATAL');
	
	private $file;
	private $loggerArray = array();
	private $globalLevel;
	
	protected function __construct($fileName, $globalLevel) {
		
		$file = fopen($fileName, 'a+');
		
		if ($file == FALSE) {
			throw new RuntimeException('LoggerFactory cannot open log file ' . $fileName);
		}
		
		$this->file = $file;
		$this->globalLevel = $globalLevel;
		
		fwrite($file, "------------\n");
	}
	
	public static function init($fileName, $globalLevel) {
		
		if (isset(self::$instance)) {
			throw new BadMethodCallException('Multiple calls to LoggerFactory::init method are forbidden');
		}
		
		self::$instance = new LoggerFactory($fileName, $globalLevel);
	}
	
	private static function getLoggerFactory() {
		
		if (!isset(self::$instance)) {
			throw new BadMethodCallException('LoggerFactory not initialized');
		}
		
		return self::$instance;
	}
	
	public static function close() {
	
		$loggerFactory = LoggerFactory::getLoggerFactory();
		
		$loggerFactory->loggerArray = array();
		fclose($loggerFactory->file);
		LoggerFactory::$instance = NULL;
	}
	
	public static function getLogger($sourceName) {
		
		$loggerFactory = LoggerFactory::getLoggerFactory();
		
		$logger = $loggerFactory->loggerArray[$sourceName];
		if ($logger == NULL) {
			$logger = new Logger($sourceName, $loggerFactory->file);
			$loggerFactory->loggerArray[$sourceName] = $logger;
		}
		
		return $logger;
	}
	
	public static function logGeneralMessage($sourceName, $message, $level) {
		
		$loggerFactory = LoggerFactory::getLoggerFactory();
		
		if ($level < $loggerFactory->globalLevel) {
			return;
		}
		
		$logLevelName = $loggerFactory::$logLevelNameArray[$level];
		
		$message = date(DATE_RFC822) . ' [' . $logLevelName . '] ' . $sourceName . ': ' . $message . "\n";
		fwrite($loggerFactory->file, $message);
	}
}
?>